/**
 * 单一化通用功能函数
 */
// url地址
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null
}
var common = {
    /**
     * 
     * @param {string} message 消息内容 
     * @param {number} type 消息类型（0：error,1:success,2:warnning)
     */
    showMsg: function (message, msgType) {
        var id = 'commonMsg_' + new Date().getTime();
        var msgHtml = `<div class="common-msg type_${msgType}" id="${id}">
                            <a class="msg-close" onclick="common.closeCommonMsg('${id}')"></a>
                            <span>${message}</span>
                        </div>`
        $('.common-msg').remove();
        $('body').append(msgHtml);
        setTimeout(() => {
            common.closeCommonMsg(id);
        }, 3000)
    },
    closeCommonMsg: function (id) {
        var idObj = document.getElementById(id);
        idObj && idObj.parentNode.removeChild(idObj);
    },
    /**
     * 确认框
     * @param {string} message 确认提示
     * @param {*} success 成功回调
     * @param {*} cancel 失败回调
     */
    confirm: function (message, success, cancel) {
        var id = 'commonMsg_' + new Date().getTime();
        var confirmHtml = `<div class="common-confirm" id="${id}">
                                <h1>提示<a class="close-btn" id="${id}_close"></a></h1>   
                                <div class="confirm-content">                      
                                    <p class="confirm-msg">${message}</p>
                                    <p>
                                        <button class="bar-button" id="${id}_y">确定</button>
                                        <button class="bar-button" id="${id}_n">取消</button>
                                    </p>
                                </div>
                            </div>`
        $('body').append(confirmHtml);
        document.getElementById(`${id}_y`).onclick = function () {
            try {
                success && success();
            } catch (error) {
                console.log('[confirm-error]')
            }
            $(`#${id}`).remove();
        };
        document.getElementById(`${id}_n`).onclick = function () {
            cancel && cancel();
            $(`#${id}`).remove();
        };
        document.getElementById(`${id}_close`).onclick = function () {
            cancel && cancel();
            $(`#${id}`).remove();
        }
    },
    showTitleTips: function () {
        $(document).on('mouseenter', '.show-title', function (e) {
            e.preventDefault();
            var $this = $(this);
            var title = $this.attr('title');
            if (title) {
                layer.tips(title, $this[0], {
                    tips: [4, '#0464b388'],
                    time: 1000
                });
            }
        })
    },
    stopPropagation: function (e) {
        var ev = e || window.event;
        if (ev && ev.stopPropagation) {
            ev.stopPropagation();
        } else {
            ev.cancelBubble = true;
        }
    },
    preventDefault: function (e) {
        var ev = e || window.event;
        if (ev.preventDefault) {
            event.preventDefault();
        }
        else {
            ev.returnValue = false;
        }
    },
    /**
     * 
     * @param {*} ele 拖动弹窗dom
     * @param {*} handler 
     */
    drag: function (ele, handler) {
        var boxX, boxY, mouseX, mouseY, offsetX, offsetY;
        var box = ele;
        if (handler) {
            // 鼠标按下的动作
            handler.onmousedown = down
        } else {
            box.onmousedown = down
        }
        // 鼠标按下后的函数,e为事件对象
        function down(e) {
            // 获取元素所在的坐标
            boxX = box.offsetLeft
            boxY = box.offsetTop
            // 获取鼠标所在的坐标
            mouseX = parseInt(getMouseXY(e).x)
            mouseY = parseInt(getMouseXY(e).y)
            // 鼠标相对元素左和上边缘的坐标
            offsetX = mouseX - boxX
            offsetY = mouseY - boxY
            // 鼠标的移动动作
            document.onmousemove = move
            // 释放鼠标的动作
            document.onmouseup = ()=>{
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
        // 鼠标移动调用的函数
        function move(e) {
            // 获取移动后的元素的坐标
            var x = getMouseXY(e).x - offsetX
            var y = getMouseXY(e).y - offsetY
            // 计算可移动位置的大小， 保证元素不会超过可移动范围
            var width = document.documentElement.clientWidth - box.offsetWidth
            var height = document.documentElement.clientHeight - box.offsetHeight
            // min方法保证不会超过右边界，max保证不会超过左边界
            x = Math.min(Math.max(0, x), width)
            y = Math.min(Math.max(0, y), height - 20)
            // 给元素及时定位
            box.style.left = x + 'px'
            box.style.top = y + 'px'
            //return false
        }
        // 函数用于获取鼠标的位置
        function getMouseXY(e) {
            var x = 0, y = 0
            e = e || window.event
            if (e.pageX) {
                x = e.pageX
                y = e.pageY
            } else {
                x = e.clientX + document.body.scrollLeft - document.body.clientLeft
                y = e.clientY + document.body.scrollTop - document.body.clientTop
            }
            return {
                x: x,
                y: y
            }
        }
    },
    /**
     * 移除实体
     * @param {*} viewer 
     * @param {*} type 不被移除的标识
     */
    removeEntities: function (viewer, type) {
        if (!viewer || !type) {
            return false;
        }
        var len = viewer.entities.values.length;
        if(viewer.entities._entities.length != 0){
            if(typeof(type) == 'string'){
                type = [type];
            }
            for(var i = len - 1;i >= 0;i--){
                var tempEntity = viewer.entities.values[i];
                var flag = 1;
                if(tempEntity._properties){
                    for(let item of type){
                        if(tempEntity.properties.hasProperty(item)){
                            flag = 0;
                            break;
                        }
                    }
                }
                flag && viewer.entities.remove(tempEntity);
            }
        }
        return true;
    },
    /**
     * 移除带有特殊标识的实体
     * @param {*} viewer 
     * @param {string} description 
     */
    removeEntitiesByDes: function (viewer, description){
        if (!viewer || !description) {
            return false;
        }
        var len = viewer.entities.values.length;
        for (var i = len - 1; i >= 0; i--) {
            var tempEntity = viewer.entities.values[i];
            if (tempEntity.description && tempEntity.description.getValue() == description) {
                viewer.entities.remove(tempEntity);
            }
        }
        return true;
    },
    // 时间格式化
    getFormatTime: function (date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1 + '').padStart(2, '0');
        var day = (date.getDate() + '').padStart(2, '0');
        var hours = (date.getHours() + '').padStart(2, '0');
        var minutes = (date.getMinutes() + '').padStart(2, '0');
        var seconds = (date.getSeconds() + '').padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    //生成唯一GUID
    guid: function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },
    /** 获取URL传参的值*/
    getParamValue: function (paramKey) {
        var paramArr = window.location.search.substr(1).split("&");
        for (var i = 0; i < paramArr.length; i++) {
            var itemArr = paramArr[i].split("=");
            if (paramKey == itemArr[0]) {
                return itemArr[1];
            }
        }
    },
}